package com.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.domain.Post;
import com.demo.domain.RegistrationInformation;
import com.demo.domain.Reply;
import com.demo.domain.ro.PageRequest;
import com.demo.domain.vo.RegistrationDisplayListView;
import com.demo.domain.vo.ReplyView;
import com.demo.service.MessageService;
import com.demo.service.PostService;
import com.demo.service.RegistrationInformationService;
import com.demo.service.ReplyService;
import com.demo.websocket.WebSocketServer;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private PostService postService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    ReplyService replyService;

    @Autowired
    private RegistrationInformationService registrationInformationService;


    /**
     * 根据当前登录用户id获取该用户收到的回复
     * @param toUid
     * @return
     */
    @GetMapping("/getReplyBytoUid")
    public Result getReplyBytoUid(@RequestParam long toUid) throws ParameterException {
        if(toUid <= 0L || String.valueOf(toUid).length() != 12) {
            throw new ParameterException("id格式错误");
        }
        List<ReplyView> replyViewList = replyService.getReplyByToUid(toUid);
        return Result.success(HttpStatus.SUCCESS, "查找回复成功", replyViewList);
    }

    /**
     * 某人的所有回复改为已读
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "某人的所有回复改为已读")
    @PostMapping("/updateViewedReplies")
    public Result updateViewedReplies(HttpServletRequest request) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        Integer i =
                replyService.updateViewedReplies(uid);
        return i == 1 ? Result.success(HttpStatus.SUCCESS, "更新成功", null) :
                Result.success(HttpStatus.SUCCESS, "更新失败", null);
    }

    /**
     * 根据用户id得到所有回复，分页
     * @param request
     * @param current
     * @param size
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "分页得到所有回复")
    @RequestMapping("/getRepliesByUser")
    public Result getReplies(HttpServletRequest request, @RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size) throws ParameterException {
        if (current <= 0 || size <= 0) {
            throw new ParameterException("分页参数无效");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null) {
            throw new ParameterException("未登录");
        }
        Page<Reply> page = replyService.getRepliesByUser(uid, current, size);
        return page != null && page.getRecords().size() > 0 ?
                Result.success(HttpStatus.SUCCESS, "查找成功", page) :
                Result.success(HttpStatus.SUCCESS, "当前用户未收到回复", new Page<>());
    }

    /**
     * 获取某人是否有未读的消息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "获取某人是否有未读的消息")
    @GetMapping("/getNotReadMessage")
    public Result getNotReadMessage(HttpServletRequest request) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        boolean hasNotRead = messageService.hasNotReadMessage(uid);
        if(hasNotRead){
            webSocketServer.sendInfo("您有未读消息",uid);
        }
        return hasNotRead == true ?
                Result.success(HttpStatus.SUCCESS, "有未读的消息",true) :
                Result.success(HttpStatus.SUCCESS, "没有未读的消息",false);
    }

    /**
     * 某人的所有申请改为已读
     *
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "某人的所有申请改为已读")
    @PostMapping("/updateViewedRegistrations")
    public Result updateViewedRegistrations(HttpServletRequest request) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        Integer i = registrationInformationService.updateViewedRegistrations(uid);
        return i == 1 ? Result.success(HttpStatus.SUCCESS, "更新成功", null) :
                Result.success(HttpStatus.SUCCESS, "更新失败", null);
    }

    /**
     * 获取某人发出的所有入队申请（队伍alive=0的不显示）
     *
     * @param current
     * @param size
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "获取某人发出的所有入队申请", description = "队伍alive=0的不显示,要有token")
    @PostMapping("/getAllRegistrationsByUid")
    public Result getAllRegistrationsByUid(int current, int size, HttpServletRequest request) throws Exception {
        if (current < 0 || size < 0) {
            throw new ParameterException("分页参数无效");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        Page<RegistrationDisplayListView> page = registrationInformationService.getDisplayRegistrations(current, size, uid);
        return page != null && page.getRecords().size() > 0 && page.getTotal() > 0 ?
                Result.success(HttpStatus.SUCCESS, "查找成功", page) :
                Result.success(HttpStatus.SUCCESS, "查找不到该用户的申请信息", new Page<>());
    }

    /**
     * 得到某一申请信息详情
     *
     * @param riId
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "获取某一申请信息详情", description = "根据riId,uid(token)")
    @PostMapping("/getOneRegistration")
    public Result getOneRegistration(Long riId, HttpServletRequest request) throws Exception {
        if (riId == null || riId < 0l) {
            throw new ParameterException("riId为空或值非法");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        RegistrationInformation registrationInformation = registrationInformationService.getOneRegistration(riId, uid);
        return registrationInformation == null ?
                Result.success(HttpStatus.BAD_REQUEST, "查找不到该申请信息", null) :
                Result.success(HttpStatus.SUCCESS, "查找成功", registrationInformation);
    }



    /**
     * 获取自己的帖子
     * @param pageRequest 不需传输orderByCommentCount
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "获取自己的帖子")
    @PostMapping(value = "/myPost")
    public Result getMyPost(@RequestBody PageRequest pageRequest, HttpServletRequest request) throws ParameterException {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        Post post = new Post();
        int pageSize = pageRequest.getPageSize();
        int currentPage = pageRequest.getCurrentPage();
        if (currentPage <= 0 || pageSize <= 0) {
            throw new ParameterException("分页信息参数无效");
        }
        IPage<Post> page;
        page = postService.getMyPost(currentPage, pageSize, post, uid);
//        如果当前页数大于总页数，访问总页数最后一页
        if (currentPage > page.getPages() && page.getPages() != 0) {
            page = postService.getMyPost((int) page.getPages(), pageSize, post, uid);
        }
        return Result.success(HttpStatus.SUCCESS, "获取数据成功", page);
    }

    /**
     * 修改申请信息
     *
     * @param registrationInformation
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "修改申请信息", description = "只有未审核的申请可以修改")
    @PostMapping("/modifyRegistration")
    public Result modifyRegisterInfo(@RequestBody RegistrationInformation registrationInformation, HttpServletRequest request) throws Exception {
        if (registrationInformation == null) {
            throw new ParameterException("registrationInformation为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        String msg = registrationInformationService.modifyRegisterInfo(registrationInformation, uid);
        return Result.success(HttpStatus.SUCCESS, msg, null);
    }

    /**
     * 取消某个申请
     *
     * @param riId
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "取消某个申请", description = "只有未审核的申请可以取消")
    @PostMapping("/cancelRegistration")
    public Result cancelRegistration(Long riId, HttpServletRequest request) throws Exception {
        if (riId == null || riId < 0l) {
            throw new ParameterException("riId为空或值非法");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        String msg = registrationInformationService.cancelRegistration(riId, uid);
        return Result.success(HttpStatus.SUCCESS, msg, null);
    }


}
